package com.sky.demo.utils.network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.util.Log;

/**
 * @ClassName: HttpPostUtil
 * @Description: TODO 网络请求类
 * @author LiBin
 * @date 2015年3月18日 上午11:29:15
 * 
 */
public class HttpPostUtil {
	private volatile static HttpPostUtil httpPostUtil;
	HttpPost httpPost;
	// private String url;
	private HttpHandler mHandler;

	public static HttpPostUtil getInstance() {

		if (httpPostUtil == null) {

			synchronized (HttpPostUtil.class) {

				if (httpPostUtil == null) {

					httpPostUtil = new HttpPostUtil();
				}
			}
		}
		return httpPostUtil;
	}

	/**
	 * post请求，有参数
	 * 
	 * @param url
	 *            请求地址
	 * @param temp
	 *            key-value参数
	 * @param handler
	 *            数据回调接口
	 */
	public void doPost(String url, List<BasicNameValuePair> temp,
			HttpHandler handler) {
		// this.url = url;
		this.mHandler = handler;
		/* 建立HTTP Post连线 */
		httpPost = new HttpPost(url);
		HttpExecute(temp);
	}

	/**
	 * post 请求，无参数模式
	 * 
	 * @param url
	 * @param handler
	 */
	public void doPost(String url, HttpHandler handler) {
		// this.url = url;
		this.mHandler = handler;
		/* 建立HTTP Post连线 */
		httpPost = new HttpPost(url);
		HttpExecute(null);
	}

	/**
	 * 添加请求头，无参数
	 * 
	 * @param url
	 *            地址
	 * @param header
	 *            请求头参数
	 * @param handler
	 *            数据回调接口
	 */
	public void headerPost(String url, List<BasicNameValuePair> header,
			HttpHandler handler) {
		// this.url = url;
		this.mHandler = handler;
		/* 建立HTTP Post连线 */
		httpPost = new HttpPost(url);
		for (BasicNameValuePair nv : header) {
			httpPost.addHeader(nv.getName(), nv.getValue());
		}
		HttpExecute(null);
	}

	/**
	 * 添加请求头，有参数
	 * 
	 * @param url
	 *            地址
	 * @param header
	 *            头
	 * @param parms
	 *            参数
	 * @param handler
	 *            监听回调
	 */
	public void headerPost(String url, List<BasicNameValuePair> header,
			List<BasicNameValuePair> parms, HttpHandler handler) {
		// this.url = url;
		this.mHandler = handler;
		/* 建立HTTP Post连线 */
		httpPost = new HttpPost(url);
		for (BasicNameValuePair nv : header) {
			httpPost.addHeader(nv.getName(), nv.getValue());
		}
		HttpExecute(parms);
	}

	/**
	 * @param params
	 *            数据请求参数
	 */
	public void HttpExecute(List<BasicNameValuePair> params) {
		new HttpExec().execute(params);
	}

	/**
	 * @param str
	 *            需要编码的数据
	 * @return
	 */
	public static String convertToUTF8(String str) {
		try {
			return new String(str.getBytes(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	private class HttpExec extends
			AsyncTask<List<BasicNameValuePair>, Void, String> {

		@Override
		protected String doInBackground(List<BasicNameValuePair>... params) {
			try {
				if (params[0] != null) {
					// 发出HTTP request
					httpPost.setEntity(new UrlEncodedFormEntity(params[0],
							"UTF-8"));
				}
				// 取得HTTP response
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpPost);
				int statusCode = httpResponse.getStatusLine().getStatusCode();
				if (statusCode == 200) {// 口200请求成功
					// 口303重定向
					// 口400请求错误
					// 口401未授权
					// 口403禁止访问
					// 口404文件未找到
					// 口500服务器错误
					// 取出回应字串
					return EntityUtils.toString(httpResponse.getEntity());
				} else {
					Log.i("TAG", "statusCode=" + statusCode);
					return "请求失败statusCode=" + statusCode;
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.i("TAG", "日志：" + e.toString());
			}
			return "请求失败";
		}

		@Override
		protected void onPostExecute(String result) {
			if (!result.startsWith("请求失败")) {
				Log.i("TAG", "success=" + result);
				mHandler.HttpSuccess(result);
			} else {
				Log.i("TAG", "faild=" + result);
				mHandler.HttpFaild(result);
			}
		}
	}

	/**
	 * 进行get请求参数	
	 * @param UrlPath  请求参数的地址
	 * @param params   请求参数名
	 * @return	解析后得到的字符串
	 * @throws UnsupportedEncodingException
	 * @date 2015/3/30
	 */
	public String doGet(String UrlPath,Map<String, String> params) throws UnsupportedEncodingException{  
        String content=null;  
        StringBuilder buf = new StringBuilder();  
        if(params!=null &params.size()!=0){  
  
            for (Map.Entry<String, String> entry : params.entrySet()) {  
                buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));  
                buf.append("&");                            
            }  
            buf.deleteCharAt(buf.length()-1);  
        }  
        content= buf.toString();  
          
        HttpClient httpClient = new DefaultHttpClient();  
        HttpGet getMethod = new HttpGet(content);  
          
        HttpResponse response = null;  
        try {  
            response = httpClient.execute(getMethod);     
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }catch (Exception e) {  
            e.printStackTrace();  
        }   
          
        if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
            try {  
                content = EntityUtils.toString(response.getEntity());  
            } catch (ParseException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
           
        return content;  
    }  
	
}
